﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

namespace ProjectClass.DAL
{
    public class CustomerRepository
    {
        public MembershipUser CreateUser(string username, string password, string email)
        {
            using (ProjectClassEntities db = new ProjectClassEntities())
            {
                try
                {
                    tbl_Users user = new tbl_Users();

                    user.Email = email;
                    user.PasswordSalt = CreateSalt();
                    user.Password = CreatePasswordHash(password, user.PasswordSalt);
                    user.CreatedDate = DateTime.Now;
                    user.IsActivated = true;
                    user.IsLockedOut = false;
                    user.LastLockedOutDate = DateTime.Now;
                    user.LastLoginDate = DateTime.Now;
                    user.NewEmailKey = GenerateKey();
                    db.tbl_Users.Add(user);
                    db.SaveChanges();

                    return GetUser(username);
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                            eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    throw;
                }

            }
        }
        public string GetUserNameByEmail(string email)
        {
            using (ProjectClassEntities db = new ProjectClassEntities())
            {
                var result = db.tbl_Users.Where(u => u.Email.Equals(email));

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();

                    return dbuser.Email;
                }
                else
                {
                    return "";
                }
            }
        }
        public MembershipUser GetUser(string email)
        {
            using (ProjectClassEntities db = new ProjectClassEntities())
            {
                var result = db.tbl_Users.Where(u => u.Email.Equals(email));

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();
                    int _providerUserKey = dbuser.UserId;
                    string _email = dbuser.Email;
                    string Displayname = dbuser.DisplayName;
                    string _passwordQuestion = "";
                    string _comment = dbuser.Comments;
                    bool? _isApproved = dbuser.IsActivated;
                    bool? _isLockedOut = dbuser.IsLockedOut;
                    DateTime? _creationDate = dbuser.CreatedDate;
                    DateTime? _lastLoginDate = dbuser.LastLoginDate;
                    DateTime? _lastActivityDate = DateTime.Now;
                    DateTime _lastPasswordChangedDate = DateTime.Now;
                    DateTime? _lastLockedOutDate = dbuser.LastLockedOutDate;
                    MembershipUser user = new MembershipUser("CustomMembershipProvider",
                                                              Displayname,
                                                              _providerUserKey,
                                                              _email,
                                                              _passwordQuestion,
                                                              _comment,
                                                              _isApproved.Value,
                                                              _isLockedOut.Value,
                                                              _creationDate.Value,
                                                              _lastLoginDate.Value,
                                                              _lastActivityDate.Value,
                                                              _lastPasswordChangedDate,
                                                              _lastLockedOutDate.Value);
                    return user;
                }
                else
                {
                    return null;
                }
            }
        }
        private static string CreateSalt()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[32];
            rng.GetBytes(buff);

            return Convert.ToBase64String(buff);
        }
        private static string CreatePasswordHash(string pwd, string salt)
        {
            string saltAndPwd = String.Concat(pwd, salt);
            return GetSwcSH1(saltAndPwd);
        }
        public static string GetSwcSH1(string value)
        {
            SHA1 algorithm = SHA1.Create();
            byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
            string sh1 = "";
            for (int i = 0; i < data.Length; i++)
            {
                sh1 += data[i].ToString("x2").ToUpperInvariant();
            }
            return sh1;
        }
        public bool ValidateUser(string email, string password)
        {
            using (ProjectClassEntities db = new ProjectClassEntities())
            {
                var result = db.tbl_Users.Where(m => m.Email.Equals(email));
                if (result.Count() != 0)
                {
                    var dbuser = result.First();

                    if (dbuser.Password == CreatePasswordHash(password, dbuser.PasswordSalt) &&
                                                                        dbuser.IsActivated == true)
                        return true;
                    else
                        return false;
                }
                else
                {
                    return false;
                }
            }
        }
        private static string GenerateKey()
        {
            Guid emailKey = Guid.NewGuid();

            return emailKey.ToString();
        }
        public bool ChangePassword(string email, string newpassword)
        {
            using (ProjectClassEntities db = new ProjectClassEntities())
            {
                var result = db.tbl_Users.Where(m => m.Email.Equals(email));
                if (result.Count() != 0)
                {
                    var dbuser = result.First();
                    dbuser.Password = CreatePasswordHash(newpassword, dbuser.PasswordSalt);
                    if (db.SaveChanges() == 1)
                    {
                        return true;
                    }
                    return false;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}
